package com.zhengshang.third.jingdong;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.domain.kplunion.CategoryService.request.get.CategoryReq;
import com.jd.open.api.sdk.domain.kplunion.CategoryService.response.get.CategoryResp;
import com.jd.open.api.sdk.domain.kplunion.GoodsService.request.query.GoodsReq;
import com.jd.open.api.sdk.domain.kplunion.GoodsService.response.query.GoodsResp;
import com.jd.open.api.sdk.domain.kplunion.promotioncommon.PromotionService.request.get.PromotionCodeReq;
import com.jd.open.api.sdk.domain.kplunion.promotioncommon.PromotionService.response.get.PromotionCodeResp;
import com.jd.open.api.sdk.request.kplunion.UnionOpenCategoryGoodsGetRequest;
import com.jd.open.api.sdk.request.kplunion.UnionOpenGoodsQueryRequest;
import com.jd.open.api.sdk.request.kplunion.UnionOpenPromotionCommonGetRequest;
import com.jd.open.api.sdk.response.kplunion.UnionOpenCategoryGoodsGetResponse;
import com.jd.open.api.sdk.response.kplunion.UnionOpenGoodsQueryResponse;
import com.jd.open.api.sdk.response.kplunion.UnionOpenPromotionCommonGetResponse;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.utils.DateUtils;
import com.zhengshang.common.utils.http.HttpUtils;
import org.springframework.stereotype.Component;

/**
 * 京东工具类
 */
@Component
public class JingDongUtils {


    /**
     * 京东应用siteId
     */
    public static final String siteId = "4100395907";
    /**
     * 京东应用appKey
     */
    public static final String appKey = "9d2a1facf67ce1ade8e6b0d04f49f0d0";

    /**
     * 京东应用密钥
     */
    public static final String appSecret = "af835ac516664374b5f5753e0d0d7a06";

    /**
     * 接口地址
     */
    public static final String baseUrl = "https://api.jd.com/routerjson";

    /**
     * 推广位Id
     */
    public static final String pid = "3004468079";

    /**
     * 授权接口地址
     * https://open-oauth.jd.com/oauth2/to_login?app_key=XXXXX&response_type=code&redirect_uri=XXXXX&state=20180416&scope=snsapi_base
     */
    public static final String oauthUrl = "https://open-oauth.jd.com/oauth2/to_login";

    /**
     * access_token接口地址
     * https://open-oauth.jd.com/oauth2/access_token?app_key=XXXXX&app_secret=XXXXX&grant_type=authorization_code&code=XXXXX
     */
    public static final String accessTokenUrl = "https://open-oauth.jd.com/oauth2/access_token";


    /**
     * 获取授权Url
     *
     * @param redirectUri 回调地址参数
     * @param scope       应用的作用域(snsapi_base|snsapi_union_login)
     * @return
     */
    private static String getOauthUrl(String redirectUri, String scope, String state) {
        String text = oauthUrl + "?app_key=%s&response_type=code&redirect_uri=%s&scope=%s&state=%s";
        String content = String.format(text, appKey, redirectUri, scope, state);
        return content;
    }

    /**
     * 获取授权OauthUrl
     *
     * @param redirectUri
     * @return
     */
    public static String getAppOauthUrl(String redirectUri, String state) {
        String oauthUrl = getOauthUrl(redirectUri, "snsapi_base", state);
        return oauthUrl;
    }


    /**
     * 根据code换取AccessToken
     * {"access_token":"3a6c3d0ad9e945f892c0d5bff597179e2yzn","expires_in":2592000,"refresh_token":"53552cc92e964a0d9fde911ca9ab7e61m1nt","scope":"snsapi_base","open_id":"TqqLlji2ydnT-XiNs8LzIS1NY0Bic84Be217TIMgPi0","uid":"4759642643","time":1649929484091,"token_type":"bearer","code":0,"xid":"o*AATRY7K8dPA_gavW88fLpibdZWE4MNAtR4la3-nEOvC8HhWoYXQ"}
     *
     * @param code
     * @return
     */
    public static String getAccessToken(String code) {
        String text = accessTokenUrl + "?app_key=%s&app_secret=%s&grant_type=authorization_code&code=%s";
        String newAccessTokenUrl = String.format(text, appKey, appSecret, code);
        System.out.println(newAccessTokenUrl);
        String result = HttpUtils.doGet(newAccessTokenUrl);
        JSONObject jsonObject = JSON.parseObject(result);
        String accessToken = jsonObject.getString("access_token");
        System.out.println(result);
        return accessToken;
    }

    /**
     * 商品搜索接口
     *
     * @param accessToken
     * @param sortName    排序字段(price：单价, commissionShare：佣金比例, commission：佣金， inOrderCount30Days：30天引单量， inOrderComm30Days：30天支出佣金)
     * @param sort        asc,desc升降序,默认降序
     * @return
     */
    public static AjaxResult goodsQuery(String accessToken, Integer pageIndex, String goodsName, String sortName, String sort, Integer isCoupon) {
        try {
            JdClient client = new DefaultJdClient(baseUrl, accessToken, appKey, appSecret);
            UnionOpenGoodsQueryRequest request = new UnionOpenGoodsQueryRequest();
            GoodsReq goodsReqDTO = new GoodsReq();
            goodsReqDTO.setKeyword(goodsName);
            goodsReqDTO.setSortName(sortName);
            goodsReqDTO.setSort(sort);
            goodsReqDTO.setIsCoupon(isCoupon);
            goodsReqDTO.setPageIndex(pageIndex);
            goodsReqDTO.setPageSize(10);
            goodsReqDTO.setPid(pid);
            request.setGoodsReqDTO(goodsReqDTO);
            request.setVersion("1.0");
            request.setSignmethod("MD5");
            request.setTimestamp(DateUtils.getTime());
            UnionOpenGoodsQueryResponse response = client.execute(request);
            int code = response.getQueryResult().getCode();
            if (code == 200) {
                System.out.println(JSON.toJSONString(response));
                GoodsResp[] data = response.getQueryResult().getData();
                return AjaxResult.success(data);
            } else {
                return AjaxResult.error("京东错误信息：" + response.getQueryResult().getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取分类
     *
     * @param accessToken
     * @return
     */
    public static AjaxResult getCategoryGoods(String accessToken) {
        try {
            JdClient client = new DefaultJdClient(baseUrl, accessToken, appKey, appSecret);
            UnionOpenCategoryGoodsGetRequest request = new UnionOpenCategoryGoodsGetRequest();
            CategoryReq req = new CategoryReq();
            req.setParentId(0);
            req.setGrade(0);
            request.setReq(req);
            request.setVersion("1.0");
            UnionOpenCategoryGoodsGetResponse response = client.execute(request);
            System.out.println(JSON.toJSONString(response));
            CategoryResp[] data = response.getGetResult().getData();
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取推广链接
     *
     * @param
     */
    public static AjaxResult getGoodsPromoteUrl(String accessToken, Long userId, String materialId, String couponUrl) {
        try {
            JdClient client = new DefaultJdClient(baseUrl, accessToken, appKey, appSecret);
            UnionOpenPromotionCommonGetRequest request = new UnionOpenPromotionCommonGetRequest();
            PromotionCodeReq promotionCodeReq = new PromotionCodeReq();
            promotionCodeReq.setMaterialId(materialId);
            promotionCodeReq.setSiteId(siteId);
            promotionCodeReq.setSubUnionId(TypeUtils.castToString(userId));
            promotionCodeReq.setCouponUrl(couponUrl);
            request.setPromotionCodeReq(promotionCodeReq);
            request.setVersion("1.0");
            UnionOpenPromotionCommonGetResponse response = client.execute(request);
            System.out.println(JSON.toJSONString(response));
            PromotionCodeResp data = response.getGetResult().getData();
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }


    public static void main(String[] args) {
        //String oauthUrl = getAppOauthUrl("https://www.baidu.com/", "");
        //System.out.println(oauthUrl);
        //getAccessToken("PMIxdy",0L);
        //goodsQuery("3a6c3d0ad9e945f892c0d5bff597179e2yzn", 1, "男装", "price", "asc", 0);
        //getGoodsPromoteUrl("", "", "https://item.jd.com/100026480142.html", "");
        getCategoryGoods("");
    }

}
